package com.adee.gulimall.product.service.impl;

import com.adee.gulimall.common.utils.PageUtils;
import com.adee.gulimall.common.utils.Query;
import com.adee.gulimall.common.constant.ProductConstant;
import com.adee.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.adee.gulimall.product.dao.AttrDao;
import com.adee.gulimall.product.dao.AttrGroupDao;
import com.adee.gulimall.product.dao.CategoryDao;
import com.adee.gulimall.product.entity.*;
import com.adee.gulimall.product.service.AttrService;
import com.adee.gulimall.product.service.CategoryService;
import com.adee.gulimall.product.service.ProductAttrValueService;
import com.adee.gulimall.product.vo.AttrGroupRelationReqVo;
import com.adee.gulimall.product.vo.AttrGroupRespVo;
import com.adee.gulimall.product.vo.AttrRespVo;
import com.adee.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrDao attrDao;

    @Autowired
    ProductAttrValueService productAttrValueService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");

        // attr_type为1表示规格参数，0表示销售属性
        wrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? 1 : 0);
        if(catelogId == 0) {
            if(!StringUtils.isEmpty(key)) {
                wrapper.like("attr_name", key)
                        .or().like("value_select", key);
            }
        } else {
            wrapper.eq("catelog_id", catelogId);
            if(!StringUtils.isEmpty(key)) {
                wrapper.and(obj -> {
                    obj.like("attr_name", key)
                            .or().like("value_select", key);
                });
            }
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> list = records.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 查询分类名
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            // 查询组名（规格参数才有分组，销售属性没有分组）
            if("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId()));
                if (attrAttrgroupRelationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    if(attrGroupEntity != null)
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            return attrRespVo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(list);
        return pageUtils;
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        // 保存基本数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity); // 相同属性名复制
        this.save(attrEntity);
        // 保存关联关系，规格参数type=1有分组，销售属性type=0没有分组
        if(attr.getAttrType() == ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity rela = new AttrAttrgroupRelationEntity();
            rela.setAttrId(attrEntity.getAttrId());
            rela.setAttrGroupId(attr.getAttrGroupId());
            relationDao.insert(rela);
        }
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        if(attrEntity == null) return null;
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        // 查询分类名
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        // 查询组名
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationDao.selectOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrEntity.getAttrId()));
        if (attrAttrgroupRelationEntity != null) {
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
            if(attrGroupEntity != null) {
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                attrRespVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
            }
        }
        // 分类完整路径
        Long[] catelogPath = categoryService.getCategoryPath(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);
        return attrRespVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        // 更新基本数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity); // 相同属性名复制
        this.updateById(attrEntity);
        // 参数规格type=1，更新关联关系
        if(attr.getAttrType() == ProductConstant.AttrTypeEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity rela = relationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrEntity.getAttrId()));
            rela.setAttrGroupId(attr.getAttrGroupId());
            relationDao.updateById(rela);
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relaList =
                relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attrGroupId));
        List<Long> attrIds = relaList.stream().map(rela -> rela.getAttrId()).collect(Collectors.toList());
        return this.listByIds(attrIds);
    }

    @Override
    public void deleteRelation(AttrGroupRelationReqVo[] attrList) {
        relationDao.deleteRelation(attrList);
    }

    // 获取当前分类中没有被其他分组关联的属性
    @Override
    public PageUtils getRelationAttrNo(Long attrGroupId, Map<String, Object> params) {
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        int page = Integer.parseInt((String)params.get("page"));
        page = page < 1 ? 1 : page;
        int limit = Integer.parseInt((String)params.get("limit"));
        int begin = (page-1)*limit;
        int size = limit;
        String key = (String)params.get("key");
        Map<String, Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("size", size);
        if(!StringUtils.isEmpty(key)) {
            map.put("key", key);
        }

        List<AttrEntity> list = attrDao.getListNo(attrGroupEntity.getCatelogId(), map);
        int totalCnt = attrDao.getListNoTotalCnt(attrGroupEntity.getCatelogId(), map);

        PageUtils pageUtils = new PageUtils(list, totalCnt, size, page);
        return pageUtils;
    }

    // 查询某个分类下所有分组及分组下所有属性
    @Override
    public List<AttrGroupRespVo> withattr(Long catelogId) {
        List<AttrGroupEntity> attrGroupList =
                attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                        .eq("catelog_id", catelogId));
        List<AttrGroupRespVo> voList = attrGroupList.stream().map(g -> {
            // 查询该group下的属性列表
            List<AttrAttrgroupRelationEntity> relas = relationDao.selectList(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_group_id", g.getAttrGroupId()));
            List<Long> attrIds = relas.stream().map(r -> r.getAttrId()).collect(Collectors.toList());
            List<AttrEntity> list =
                    attrDao.selectList(new QueryWrapper<AttrEntity>()
                            .in("attr_id", attrIds)
                            .eq("attr_type", 1));
            AttrGroupRespVo vo = new AttrGroupRespVo(g);
            vo.setAttrs(list);
            return vo;
        }).collect(Collectors.toList());

        return voList;
    }

    @Override
    public String getNameById(Long attrId) {
        AttrEntity attrEntity = attrDao.selectById(attrId);
        if(attrEntity == null) return null;
        return attrEntity.getAttrName();
    }

    @Override
    public List<ProductAttrValueEntity> queryBaseList4Spu(Long spuId) {
        List<ProductAttrValueEntity> list = productAttrValueService.getBaseMapper().selectList(
                new QueryWrapper<ProductAttrValueEntity>()
                        .eq("spu_id", spuId));
        return list;
    }

    @Transactional
    @Override
    public void updateAttrsBySpuId(List<ProductAttrValueEntity> attrs, Long spuId) {
        productAttrValueService.remove(
                new UpdateWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        productAttrValueService.saveBatch(attrs.stream().map(a -> {
            a.setSpuId(spuId);
            return a;
        }).collect(Collectors.toList()));
    }

}